package 代码记录.指定公司代码练习记录.华为_2024.分值100.第36start;

import java.util.Scanner;

/**
 * @author zx
 * @create 2024-02-16 13:14
 * 人家的思路，自己看懂了，不难
 */
public class 悄悄话花费的时间_49 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String[] temp = sc.nextLine().split(" ");
        int[] arr = new int[temp.length];
        for(int i = 0;i < arr.length;i++){
            arr[i] = Integer.parseInt(temp[i]);
        }
        // 构建二叉树
        TreeNode root = buildTree(arr, 0);
        // 计算所有节点接收悄悄话的时间
        int res = calTime(root);
        // 输出结果
        System.out.println(res);
    }
    private static int calTime(TreeNode root) {
        if (root == null) {
            return 0;
        }
        // 递归计算左子树和右子树的接收时间
        int leftTime = calTime(root.left);
        int rightTime = calTime(root.right);
        // 当前节点的接收时间等于左右子树中较大的接收时间加上当前节点的值
        int time = Math.max(leftTime, rightTime) + root.val;
        return time;
    }
    // 构建二叉树
    private static TreeNode buildTree(int[] arr, int index) {
        if(index >= arr.length){
            return null;
        }
        TreeNode root = new TreeNode(arr[index]);
        root.left = buildTree(arr, 2 * index + 1);
        root.right = buildTree(arr, 2 * index + 2);
        return root;
    }

    static class TreeNode {
        int val;
        TreeNode left, right;

        public TreeNode(int val) {
            this.val = val;
            this.left = null;
            this.right = null;
        }
    }
}
